# -*- coding: utf-8 -*-
import re
from django.forms import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.contrib.contenttypes import generic
from django.forms.models import BaseInlineFormSet
from WebSite.models import News, Question, Quiz, UserProfile, Doubts

__author__ = 'Nataliel Vasconcelos'

def publicar(ModelAdmin, request, queryset):
    queryset.update(publish = True)

def despublicar(ModelAdmin, request, queryset):
    queryset.update(publish = False)

class NewsAdmin(admin.ModelAdmin):
    class Media:
        js = ('/js/tiny_mce/tiny_mce.js', '/js/textareas.js')
    fieldsets = [
        ('Infomações Principais',{'fields':(('publish','detach'),('title','subTitle'),'content','date')}),
        ('Imagem Destaque',{'fields':['imageDetach']})
    ]
    list_display = ('title','subTitle','date','publish','detach')
    list_filter = ['publish','date']

    search_fields = ['title']
    actions = [publicar, despublicar]
    save_on_top = True

class QuestionInlineFormset(BaseInlineFormSet):
    def clean(self):
        count = 0
        for form in self.forms:
            try:
                if form.cleaned_data:
                    valid_correct_answer = False
                    for key in form.cleaned_data:
                        regex = re.compile( 'answer(\d+)' )
                        matcher = regex.match( key )
                        if matcher and form.cleaned_data[key] is not u"" :
                            if matcher.group(1) == form.cleaned_data['correct_answer'] :
                                valid_correct_answer = True
                    count += 1
            except AttributeError:
                pass
        if count < 1:
            raise forms.ValidationError('Informe pelo menos uma questão')
        if not valid_correct_answer:
            raise forms.ValidationError('Campo \'Resposta Correta\' está inválido')


class QuestionInline(admin.StackedInline):
    model = Question
    formset = QuestionInlineFormset

class QuizView(admin.ModelAdmin):
    fields = [ 'title' ]
    inlines = [ QuestionInline ]

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    can_delete = False
    verbose_name_plural = 'profile'

# Define a new User admin
class UserAdmin(UserAdmin):
    inlines = (UserProfileInline, )

class DoubtsAdmin(admin.ModelAdmin):
    class Media:
        js = ('/js/tiny_mce/tiny_mce.js', '/js/textareas.js')
    fieldsets = [
        ('Infomações Principais',{'fields':(('publish','title','content'))}),
    ]
    list_display = ('title','publish')
    list_filter = ['publish','date']

    search_fields = ['title']
    actions = [publicar, despublicar]
    save_on_top = True

# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
admin.site.register(Quiz, QuizView)
admin.site.register(News, NewsAdmin)
admin.site.register(Doubts, DoubtsAdmin)